package GUI;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Set;
import java.util.TreeMap;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import msgParser.Message;
import msgParser.Parser;
import msgParser.Strings;
import msgParser.Validation;

import Core.Connection;
import Core.Rank;
import Core.SessionData;

public class SubForumModeratorsMenu extends AbstractMenu
{
	private JLabel label;
	private JButton disconnectButton;
	private JLabel userMode;
	private JButton refreshButton;
	private JLabel forumUsers;
	private JList<String> userList;
	private JScrollPane userListScroll;
	private JButton forumButton;
	private JButton subForumButton;
	private JButton addModeratorButton;
	private JButton removeModeratorButton;
	private JButton logoutButton;
	private JLabel moderatorsLabel;
	private JList<String> moderatorList;
	private JScrollPane moderatorListScroll;
	
	DefaultListModel<String> userListModel = new DefaultListModel<String>();  
	DefaultListModel<String> moderatorListModel = new DefaultListModel<String>();  
	
	public SubForumModeratorsMenu(JFrame frame) 
	{
		super(frame);
		label = new JLabel("Moderators Management");
		label.setBounds(230,30,380,30);
		label.setFont(new Font(label.getFont().getName(),label.getFont().getStyle(), 30));
		
		userMode = new JLabel(MainWindow.data.rank.toString() + " mode");
		userMode.setBounds(10,500,200,30);
		userMode.setFont(new Font(userMode.getFont().getName(),userMode.getFont().getStyle(), 15));
		userMode.setForeground(new Color(0, 0, 255));
		
		forumUsers = new JLabel("All members:");
		forumUsers.setBounds(351,170,300,30);
		forumUsers.setFont(new Font(forumUsers.getFont().getName(),forumUsers.getFont().getStyle(), 15));
		
		moderatorsLabel = new JLabel("Moderators:");
		moderatorsLabel.setBounds(510,170,300,30);
		moderatorsLabel.setFont(new Font(moderatorsLabel.getFont().getName(),moderatorsLabel.getFont().getStyle(), 15));
		
		forumButton = new JButton("Back to Forum");
		forumButton.setBounds(25, 200, 130, 20);
		forumButton.addActionListener(new ActionListener() 
		{
            public void actionPerformed(ActionEvent e)
            {
            	MainWindow.switchMenu(new ForumMenu(getFrame()));
            }
		});
		
		subForumButton = new JButton("Back to " + MainWindow.data.currentSubForum);
		subForumButton.setBounds(25, 170, 130, 20);
		subForumButton.addActionListener(new ActionListener() 
		{
            public void actionPerformed(ActionEvent e)
            {
            	MainWindow.switchMenu(new SubForumMenu(getFrame()));
            }
		});
		
		/*createSubForum = new JButton("Create");
		createSubForum.setBounds(350, 430, 100, 30);
		createSubForum.setFont(new Font(createSubForum.getFont().getName(),Font.BOLD, 15));
		createSubForum.setForeground(new Color(255, 0, 0));
		createSubForum.addActionListener(new ActionListener() 
		{
            public void actionPerformed(ActionEvent e)
            {
            	String name = subForumName.getText();
            	if(!Validation.validateString(name, Validation.CHAR_FIRST | Validation.HAS_LETTERS | Validation.NO_SYMBOLS))
            	{
            		JOptionPane.showMessageDialog(null, "Sub-Forum name must start with a letter and contain no symbols.", "Bad Sub-Forum Name", JOptionPane.ERROR_MESSAGE);
            		return;
            	}
            	if(userList.getSelectedIndex() == -1)
            	{
            		JOptionPane.showMessageDialog(null, "Please select a moderator.", "Error", JOptionPane.ERROR_MESSAGE);
            		return;
            	}
            	String moderator = userList.getSelectedValue();
            	Connection.send(Message.createMessage(Strings.ADD_SUBFORUM, name, ""+MainWindow.data.forums.get(MainWindow.data.currentForum), ""+MainWindow.data.forumUsers.get(moderator)));
            }
		});
		*/
		logoutButton = new JButton("Log out");
		logoutButton.setBounds(25, 140, 100, 20);
		logoutButton.addActionListener(new ActionListener() 
		{
            public void actionPerformed(ActionEvent e)
            {
            	Connection.send(Message.createMessage(Strings.LOGOUT));
            }
		});
		
		disconnectButton = new JButton(new ImageIcon("disconnect.PNG"));
		disconnectButton.setBounds(10, 530, 32, 32);
		disconnectButton.setContentAreaFilled(false);
		disconnectButton.setBorder(null);
		disconnectButton.addMouseListener(new MouseAdapter() 
		{
		    public void mousePressed(MouseEvent evt) 
		    {
		    	disconnectButton.setIcon(new ImageIcon("disconnect2.PNG"));
            	disconnectButton.repaint();
		    }
		    public void mouseReleased(MouseEvent evt) 
		    {
		    	Point p = evt.getPoint();
		    	disconnectButton.setIcon(new ImageIcon("disconnect.PNG"));
            	disconnectButton.repaint();
		    	if(p.x < 0 || p.y < 0 || p.x > disconnectButton.getWidth() || p.y > disconnectButton.getHeight()) return;
            	Connection.disconnect();
            	MainWindow.data = new SessionData();
            	MainWindow.switchMenu(new ConnectMenu(getFrame()));
		    }
		});
		
		refreshButton = new JButton(new ImageIcon("refresh.PNG"));
		refreshButton.setBounds(650, 370, 30, 30);
		refreshButton.addActionListener(new ActionListener() 
		{
            public void actionPerformed(ActionEvent e)
            {
            	Connection.send(Message.createMessage(Strings.SHOW_FORUM_USERS, ""+MainWindow.data.forums.get(MainWindow.data.currentForum)));
            }
		});
		
		userList = new JList<String>(userListModel);
		userList.setBorder(new EmptyBorder(4,4,4,4));
		userList.setFixedCellHeight(30);
		userList.setFixedCellWidth(100);
		//subForumList.setBounds(350, 140, 300, 400);
		userList.setFont(new Font("Courier New",userList.getFont().getStyle(), 18));
		userListScroll = new JScrollPane(userList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		userListScroll.setPreferredSize(new Dimension(300, 100));
		userListScroll.setBounds(350, 200, 140, 200);
		
		moderatorList = new JList<String>(moderatorListModel);
		moderatorList.setBorder(new EmptyBorder(4,4,4,4));
		moderatorList.setFixedCellHeight(30);
		moderatorList.setFixedCellWidth(100);
		//subForumList.setBounds(350, 140, 300, 400);
		moderatorList.setFont(new Font("Courier New",moderatorList.getFont().getStyle(), 18));
		moderatorListScroll = new JScrollPane(moderatorList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		moderatorListScroll.setPreferredSize(new Dimension(300, 100));
		moderatorListScroll.setBounds(510, 200, 140, 200);
		
		addModeratorButton = new JButton("Add Moderator");
		addModeratorButton.setBounds(350, 430, 140, 30);
		addModeratorButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0) 
			{
				int sel_user = userList.getSelectedIndex();
				if(sel_user == -1) JOptionPane.showMessageDialog(null, "Please select a user from the list.", "Unexpected error", JOptionPane.ERROR_MESSAGE);
				else Connection.send(Message.createMessage(Strings.ADD_MODERATOR, ""+MainWindow.data.forumUsers.get(userList.getSelectedValue()), ""+MainWindow.data.subForums.get(MainWindow.data.currentSubForum)));
			}
		});
		
		removeModeratorButton = new JButton("Remove Moderator");
		removeModeratorButton.setBounds(510, 430, 170, 30);
		removeModeratorButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0) 
			{
				int sel_mod = moderatorList.getSelectedIndex();
				if(sel_mod == -1) JOptionPane.showMessageDialog(null, "Please select a moderator from the list.", "Unexpected error", JOptionPane.ERROR_MESSAGE);
				else Connection.send(Message.createMessage(Strings.REMOVE_MODERATOR, ""+MainWindow.data.forumUsers.get(moderatorList.getSelectedValue()), ""+MainWindow.data.subForums.get(MainWindow.data.currentSubForum)));
			}
		});
	}

	public void connectionInterrupted() 
	{
		JOptionPane.showMessageDialog(null, "Connection has crashed. Please reconnect...", "Connection Error", JOptionPane.ERROR_MESSAGE);
		MainWindow.switchMenu(new ConnectMenu(getFrame()));
	}

	public void incomingMessage(String msg) 
	{
		Parser p = new Parser(msg);
		p.Parse();
		try 
		{
			if(p.testHeader(Strings.ANS_SHOW_FORUM_USERS))
			{
				userListModel.clear();
				userListModel.addElement("FIX");
				userListModel.remove(0);
				TreeMap<String, Integer> forumUsers = new TreeMap<String, Integer>();
				for(int i = 1; i < p.getSize(); i+=2) 
				{
					forumUsers.put(p.argStr(i), p.argInt(i+1));
					userListModel.addElement(p.argStr(i));
				}
				MainWindow.data.forumUsers = forumUsers;
				
			}
			else if(p.testHeader(Strings.ERROR_GET_SUBFORUM_MODERATORS))
			{
				JOptionPane.showMessageDialog(null, "Error: " + p.argStr(1), "Unexpected error", JOptionPane.ERROR_MESSAGE);
			}
			else if(p.testHeader(Strings.ERROR_SHOW_FORUM_USERS))
			{
				JOptionPane.showMessageDialog(null, "Error: " + p.argStr(1), "Unexpected error", JOptionPane.ERROR_MESSAGE);
			}
			else if(p.testHeader(Strings.ANS_GET_SUBFORUM_MODERATORS))
			{
				moderatorListModel.clear();
				moderatorListModel.addElement("FIX");
				moderatorListModel.remove(0);
				MainWindow.data.SubForumModeratorIds.clear();
				for(int i = 1; i < p.getSize(); i++) 
				{
					MainWindow.data.SubForumModeratorIds.add(p.argInt(i));
					Set<String> ks = MainWindow.data.forumUsers.keySet();
					for(String s : ks)
					{
						if(MainWindow.data.forumUsers.get(s).intValue() == p.argInt(i))
							moderatorListModel.addElement(s);
					}
					
				}
			}
			else if(p.testHeader(Strings.LOGGED_OUT))
			{
				MainWindow.data.loggedIn = false;
				MainWindow.data.rank = Rank.GUEST;
				JOptionPane.showMessageDialog(null, "You have logged out of the system.", "Logged out", JOptionPane.INFORMATION_MESSAGE);
				MainWindow.switchMenu(new LobbyMenu(getFrame()));
			}
			else if(p.testHeader(Strings.ERROR_LOG_OUT))
			{
				JOptionPane.showMessageDialog(null, "Logout error: " + p.argStr(1), "Unexpected error", JOptionPane.ERROR_MESSAGE);
			}
			else if(p.testHeader(Strings.SUBFORUM_ADDED))
			{
				JOptionPane.showMessageDialog(null, "Sub-Forum has been succesfuly added.", "Success", JOptionPane.INFORMATION_MESSAGE);
				MainWindow.switchMenu(new ForumMenu(getFrame()));
			}
			else if(p.testHeader(Strings.ERROR_ADD_SUBFORUM))
			{
				JOptionPane.showMessageDialog(null, "Error: " + p.argStr(1), "Error", JOptionPane.ERROR_MESSAGE);
			}
			else if(p.testHeader(Strings.ERROR_ADD_MODERATOR))
			{
				JOptionPane.showMessageDialog(null, "Error: " + p.argStr(1), "Error", JOptionPane.ERROR_MESSAGE);
			}
			else if(p.testHeader(Strings.ERROR_REMOVE_MODERATOR))
			{
				JOptionPane.showMessageDialog(null, "Error: " + p.argStr(1), "Error", JOptionPane.ERROR_MESSAGE);
			}
			else if(p.testHeader(Strings.MODERATOR_ADDED))
			{
				JOptionPane.showMessageDialog(null, "Successfully added.", "Success", JOptionPane.INFORMATION_MESSAGE);
				Connection.send(Message.createMessage(Strings.SHOW_FORUM_USERS, ""+MainWindow.data.forums.get(MainWindow.data.currentForum)));
				Connection.send(Message.createMessage(Strings.GET_SUBFORUM_MODERATORS, ""+MainWindow.data.subForums.get(MainWindow.data.currentSelectedSubForum)));
			}
			else if(p.testHeader(Strings.MODERATOR_REMOVED))
			{
				JOptionPane.showMessageDialog(null, "Successfully removed.", "Success", JOptionPane.INFORMATION_MESSAGE);
				Connection.send(Message.createMessage(Strings.SHOW_FORUM_USERS, ""+MainWindow.data.forums.get(MainWindow.data.currentForum)));
				Connection.send(Message.createMessage(Strings.GET_SUBFORUM_MODERATORS, ""+MainWindow.data.subForums.get(MainWindow.data.currentSelectedSubForum)));
			}
		} 
		catch (Exception e) {}
	}

	public void create() 
	{
			regItem(label);
			regItem(logoutButton);
			regItem(userListScroll);
			regItem(moderatorListScroll);
			regItem(refreshButton);
			regItem(disconnectButton);
			regItem(userMode);
			regItem(moderatorsLabel);
			regItem(forumButton);
			regItem(forumUsers);
			regItem(addModeratorButton);
			regItem(removeModeratorButton);
			regItem(subForumButton);
			getFrame().repaint();
		Connection.send(Message.createMessage(Strings.SHOW_FORUM_USERS, ""+MainWindow.data.forums.get(MainWindow.data.currentForum)));
		Connection.send(Message.createMessage(Strings.GET_SUBFORUM_MODERATORS, ""+MainWindow.data.subForums.get(MainWindow.data.currentSelectedSubForum)));
	}

}
